#include <49func.h>
#define NUM 10000000
int main()
{
    int shmid = shmget(IPC_PRIVATE,4096,IPC_CREAT|0600);
    ERROR_CHECK(shmid,-1,"shmget");
    int *p = (int *)shmat(shmid,NULL,0);
    p[0] = 0; // 统计总次数
    p[1] = 0; // wants_to_enter[0]
    p[2] = 0; // wants_to_enter[1]
    p[3] = 0; // turn
    if(fork() == 0){
        /*
          wants_to_enter[0] ← true
          while wants_to_enter[1] {
              if turn ≠ 0 {
                  wants_to_enter[0] ← false
                  while turn ≠ 0 {
                   // busy wait
                  }
                  wants_to_enter[0] ← true
              }
          }
         // critical section p[0]++ 写在这个位置...
          turn ← 1
          wants_to_enter[0] ← false// remainder section
         * */
        for(int i = 0; i < NUM; ++i){
            p[1] = 1;
            while(p[2]){
                if(p[3] != 0){
                    p[1] = 0;
                    while(p[3] != 0){}
                    p[1] = 1;
                }
            }
            ++p[0];
            p[3] = 1;
            p[1] = 0;
        }
    }
    else{
        for(int i = 0; i < NUM; ++i){
            p[2] = 1;
            while(p[1]){
                if(p[3] != 1){
                    p[2] = 0;
                    while(p[3] != 1) {}
                    p[2] = 1;
                }
            }
            ++p[0];
            p[3] = 0;
            p[2] = 0;
        }
        wait(NULL);
        printf("p[0] = %d\n", p[0]);
    }
    return 0;
}

